<?php
require_once __DIR__ . '/../models/UserPost.php';

class UserPostController
{
	private $db;
	private $userPostModel;

	public function __construct($db)
	{
		$this->db = $db;
		$this->userPostModel = new UserPost($db);
	}

	/**
	 * 获取用户帖子
	 */
	public function getUserPosts()
	{
		try {
			// 验证用户是否登录
			if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
				throw new Exception('未提供授权令牌');
			}

			$token = str_replace('Bearer ', '', $_SERVER['HTTP_AUTHORIZATION']);

			// 获取用户ID
			$userId = $this->userPostModel->getUserIdFromToken($token);
			if (!$userId) {
				throw new Exception('无效的用户令牌');
			}

			// 获取用户帖子数据
			$posts = $this->userPostModel->getPostsByUserId($userId);

			$this->sendResponse($posts);
		} catch (Exception $e) {
			$this->handleError($e);
		}
	}

	/**
	 * 统一响应方法
	 */
	private function sendResponse($data)
	{
		header('Content-Type: application/json');

		if (empty($data)) {
			http_response_code(200);
			echo json_encode([
				'status' => 'success',
				'count' => 0,
				'data' => []
			], JSON_UNESCAPED_UNICODE);
			return;
		}

		http_response_code(200);
		echo json_encode([
			'status' => 'success',
			'count' => count($data),
			'data' => $data
		], JSON_UNESCAPED_UNICODE);
	}

	/**
	 * 统一错误处理
	 */
	private function handleError($e)
	{
		error_log("[UserPost Controller] 错误: " . $e->getMessage());
		http_response_code(401); // 未授权
		echo json_encode([
			'status' => 'error',
			'message' => $e->getMessage()
		], JSON_UNESCAPED_UNICODE);
	}
}